package com.example.lmy.customview.OkHttp;

/**
 * @功能:
 * @Creat 2019/05/09 10:04
 * @User Lmy
 * @By Android Studio
 */

import android.content.Context;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 功能：
 *
 * @author：zhangerpeng
 * @create：2018\9\25 0025 11:15
 * @version：2018 1.0
 * Created with IntelliJ IDEA
 */
public class JsonUtils {

    public static final String ERRPR = "error";
    public static final String CODE = "code";
    public static final String DATA = "data";

    public static void processStringResult(String result, Map<String, String> uiMap, Context context, OnProcessStringListener listener) {
        try {
            String errors = "";//用于拼接错误信息的字符串
            Gson gson = new Gson();
            Map<String, Object> errorMap = gson.fromJson(result, Map.class);//错误数据
            Map<String, String> verifyErrrorMap;//返回错误信息中error中的map
            if (errorMap.get(CODE).equals("200")) {
                listener.onSucceed(result);
            } else if (errorMap.get(CODE).equals("20000")) {
                if (uiMap == null) {
                    listener.onFailure(errors + errorMap.get(ERRPR).toString());
                    Toast.makeText(context, errors + errorMap.get(ERRPR).toString(), Toast.LENGTH_SHORT).show();
                    return;
                }
                verifyErrrorMap = (Map<String, String>) errorMap.get(ERRPR);
                Set set = uiMap.keySet();
                Iterator iter = set.iterator();
                while (iter.hasNext()) {
                    String key = (String) iter.next();
                    if (verifyErrrorMap.get(key) != null) {
                        errors = uiMap.get(key) + ":" + verifyErrrorMap.get(key);
                    }
                }
                listener.onFailure(errors);
                Toast.makeText(context, errors, Toast.LENGTH_SHORT).show();
            } else {
                listener.onFailure(errors + errorMap.get(ERRPR).toString());
                Toast.makeText(context, errors + errorMap.get(ERRPR).toString(), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public interface OnProcessStringListener {
        void onSucceed(String data) throws Exception;

        void onFailure(String error);
    }

}
